package com.bigshen.algorithm.gTree.solution02PreorderTraversal;

import java.util.ArrayList;
import java.util.List;
import java.util.Stack;

public class Solution {

    class TreeNode {
        int val;
        TreeNode left;
        TreeNode right;
        public TreeNode(int val) {
            this.val = val;
        }
    }

    // 前序遍历
    public List<Integer> preorderTraversal(TreeNode root) {
        List<Integer> list = new ArrayList<>();

        if (null == root) {
            return list;
        }

        // 递归实现
        //preorder(root, list);

        // Stack实现
        Stack<TreeNode> stack = new Stack();
        stack.push(root);
        while(!stack.isEmpty()) {
            TreeNode node = stack.pop();
            list.add(node.val);
            // 栈，先进后出，优先加入right
            if (null != node.right) {
                stack.push(node.right);
            }
            if (null != node.left) {
                stack.push(node.left);
            }
        }

        return list;
    }

    private void preorder(TreeNode node, List<Integer> list) {

        if (null == node) {
            return;
        }

        list.add(node.val);
        preorder(node.left, list);
        preorder(node.right, list);
    }

}
